package panda.metainfo;

import java.util.HashMap;
import java.util.Map;

import panda.record.RecordFile;
import panda.record.TableToken;
import panda.server.Panda;
import panda.transaction.Transaction;

public class StaticManager {
	private TableManager tblmgr;
	private Map<String, StaticInfo> tablestat;
	private int callcount;

	StaticManager(TableManager tm, Transaction tx) {
		tblmgr = tm;
//		updateStats(tx);
	}

	public synchronized StaticInfo getStaticInfo(String tblname, TableToken tt,
			Transaction tx) {
		callcount++;
		if (tablestat == null || callcount > 150) {
			updateStats(tx);
		}
		StaticInfo si = tablestat.get(tblname);
		if (si == null) {
			updateTable(tblname, tx);
			si = tablestat.get(tblname);
		}
		return si;
	}

	private synchronized void updateStats(Transaction tx) {
		tablestat = new HashMap<String, StaticInfo>();
		callcount = 0;
//		TableToken tt = tblmgr.getTableToken("tblInfo", tx);
		for (String s : Panda.getMetaInfoManager().getAllTableNames(tx))
			if (!s.equals("tblInfo") && !s.equals("rdInfo"))
				tablestat.put(s, updateTable(s, tx));
//		}
//		rf.close();
	}

	private synchronized StaticInfo updateTable(String tblname, Transaction tx) {
//		System.out.println("UPDATED");
		int numOfRecord = 0;
		TableToken tt = tblmgr.getTableToken(tblname, tx);
		RecordFile rf = new RecordFile(tt, tx);
		while (rf.next()) {
			numOfRecord++;
		}
		int blknum = rf.getCursor().getBlockNum();
		
		return new StaticInfo(blknum, numOfRecord);
	}
}